package com.tul.exercise.base.thread.exercise;

import org.springframework.util.StopWatch;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程池运行休眠随机时间的任务
 */
public class Eg4 {

    public static void main(String[] args) {
        // 线程池
        ExecutorService exec = Executors.newCachedThreadPool();

        // 提交任务
        for (int i = 0; i < 10; i++) {
            exec.execute(new SleepRandomTimeTask(i + 1));
        }

        // 关闭线程池
        exec.shutdown();
    }
}

/**
 * 任务
 */
class SleepRandomTimeTask implements Runnable {
    /**
     * 随机数生成器
     */
    private static Random random = new Random(47);

    // 休眠时间
    private int sleepTime;

    public SleepRandomTimeTask(int time) {
        this.sleepTime = time;
    }

    @Override
    public void run() {

        try {
            // 计时器
            StopWatch sw = new StopWatch("测试休眠");
            sw.start();

            TimeUnit.SECONDS.sleep(random.nextInt(sleepTime));
            sw.stop();

            System.out.println(sw.prettyPrint());

        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }
}
